#!/usr/bin/python3
from itsdangerous import json
from requests.auth import HTTPBasicAuth
from lxml import etree
from base import http
from settings import ACCOUNT, PASSWORD


class OpensuseObsAPI:
    """
    opensuse obs中的相关接口操作
    """

    host = "http://117.78.1.88/"

    def __init__(self, project=None, account=None, password=None) -> None:
        self._project = project
        self._account = account or ACCOUNT
        self._password = password or PASSWORD
        self.file_size = 1024 * 20

    def _url(self, url, **kwargs):
        return self.host + url.format(**kwargs)

    @property
    def _auth(self):
        return HTTPBasicAuth(self._account, self._password)

    @staticmethod
    def _xpath(xpath, node, all=False):
        try:
            element_result = node.xpath(xpath)
            return element_result if all else element_result[0]
        except IndexError:
            return None


    def test(self):
        # GET /search/released/binary
        url = self._url(url="build/{project}/_result", project=project_name)
        response = http.get(url, auth=self._auth)

    def get_unresolvable(self, project_name=None):
        """
        获取某一个工程下的所有unresolvable的包信息
        """
        if not project_name:
            project_name = self._project
        url = self._url(url="build/{project}/_result", project=project_name)
        response = http.get(url, auth=self._auth)

        if response.status_code != 200:
            return None
        pkgs = dict()
        
        etree_element = etree.HTML(response.text)
        state = etree_element.xpath("//@state")[1:]
        # self.obs_states.append([project_name, self._parse_arch_state(state)])
        obs_info = list()
        for _result in self._xpath(xpath="//result", node=etree_element, all=True):
            for status in self._xpath(xpath="./status", node=_result, all=True):
                build_requires = list()
                build_require = (
                    self._xpath(xpath="./details/text()", node=status)
                    if self._xpath(xpath="./@code", node=status) == "unresolvable"
                    else []
                )
                if build_require:
                    for provides in build_require.split(","):
                        build_requires.append(
                            provides.replace("nothing provides", "").strip()
                        )
                pkgs = dict(
                    architecture=self._xpath(xpath="./@repository", node=_result),
                    repo_name=self._xpath(xpath="./@package", node=status),
                    build_status=self._xpath(xpath="./@code", node=status),
                    obs_branch=project_name,
                    build_requires=build_requires,
                )
                obs_info.append(pkgs)
        return obs_info
    def parse_unresolvable_package(self,project):
        pkgs=self.get_unresolvable(project_name=project)
        positive_un_package=dict()
        # reverse_un_package=list()
        for pkg in pkgs:
            if pkg["build_status"]=="unresolvable":
                pks=list()
                for pacakge in pkg["build_requires"]:
                    if "needed by" in pacakge:
                        pks.append(pacakge)
                        # reverse_un_package.append({pacakge.split()[0]:pkg["repo_name"]})
                    else:
                        pks.append(pacakge)
                positive_un_package[pkg["repo_name"]]=pkgs
                # positive_un_package.append({pkg["repo_name"]:pks})
        return positive_un_package
        


obs=OpensuseObsAPI()
pkgs=obs.parse_unresolvable_package("openEuler:22.03:LTS:LoongArch")

print(len(pkgs))
with open("bdddddddd.json","w") as file:
    json.dump(pkgs,file,indent=4)